<template>
  <div id="wrapper" v-cloak>
        <!-- 主体区域 -->
        <el-main style="background-color: rgba(28, 158, 209, 0.404)">
          <el-col :span="24">
            <el-card
              style="
                width: 800px;
                height: 820px;
                margin: 0px auto;
                border-radius: 20px;
                box-shadow: 0 0 10px #ccc;
              "
            >
              <div
                style="
                  text-align: center;
                  font-size: 18px;
                  line-height: 50px;
                  margin-top: -20px
                "
              >
                <img src="@/assets/images/team/susu1.jpg" style="height:100px;width:100px;border-radius: 50px;margin-right: 20px;margin-top: 10px;">
                <span class="text">苏苏小可爱(客服)</span>
                 <el-divider></el-divider>
              </div>
              <div style="margin-top: 10px;">
              <div style="height: 500px; overflow: auto" id="im-box"></div>
              
                <el-input
                  @keyup.enter.native="send"
                  style="margin-top: 20px;"
                  type="textarea"
                  :rows="5"
                  placeholder="请输入内容,enter键发送消息"
                  v-model="text"
                >
                </el-input>
                </div >
            </el-card>
          </el-col>
        </el-main>
  </div>
</template>

<script>
import API from "@/api/request";

export default {
  name: "BookShopChat",

  components: {},

  directives: {},
  watch: {
    users: function (val) {
      console.log(val);
    },
  },
  data() {
    return {
      user: {},
      users: [],
      chatUser: {},
      text: "",
      socket: {},
    };
  },

  mounted() {},
  created() {
    this.user = sessionStorage.getItem("user1")
      ? JSON.parse(sessionStorage.getItem("user1"))
      : {};
    this.openSocket();
    this.chat('admin')
  },
  methods: {
    getUsers(users) {
      this.users = users;
    },
    sendMessage(username, text) {
      let userStr = sessionStorage.getItem("user1");
      if (userStr) {
        let user = JSON.parse(userStr);
        if (typeof WebSocket == "undefined") {
          console.log("您的浏览器不支持WebSocket");
        } else {
          console.log("您的浏览器支持WebSocket");
          let message = { from: user.userUsername, to: username, text: text };
          this.socket.send(JSON.stringify(message));
        }
      }
    },
    openSocket() {
      let username = JSON.parse(sessionStorage.getItem("user1")).userUsername;
      console.log(username);
      if (typeof WebSocket == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      } else {
        console.log("您的浏览器支持WebSocket");
        let socketUrl = "ws://39.108.99.135:9999/imserver/" + username;
        if (this.socket != null) {
          //   this.socket.close();
          this.socket = null;
        }
        this.socket = new WebSocket(socketUrl);
        //打开事件
        this.socket.onopen = function () {
          console.log("websocket已打开");
        };
        let that = this;
        //获得消息事件
        this.socket.onmessage = function (msg) {
          let data = JSON.parse(msg.data);

          if (data.users) {
            this.users = data.users;
            //   ? data.users.filter((user) => {
            //       console.log(user.username+"-----------"+username);
            //       user.username !== username})
            //   : [];
            that.getUsers(this.users);
          } else {
            $("#im-box").append(
              $(
                `<p style="margin:15px 0;clear: both;"><el-row>` +
                  `<img src="http://39.108.99.135:9999/files/${that.chatUser.avatar}" alt="" style="width: 80px; height: 80px; border-radius: 50%;">` +
                  `<span style="margin-left:20px; border: 1px solid rgba(189, 100, 28, 0.295);
                    background-color: rgba(189, 100, 28, 0.199);
                    border-radius:60px ;
                    color: rgb(170, 62, 12);
                    padding: 10px;">${data.text}</span>` +
                  `</el-row></p>`
              )
            );
          }
        };
        //关闭事件
        // this.socket.onclose = function () {
        //   console.log("websocket已关闭");
        // };
        //发生了错误事件
        this.socket.onerror = function () {
          console.log("websocket发生了错误");
        };
      }
    },
    chat(username) {
      API.get(`/api/user/findByUsername/${username}`).then((res) => {
        this.chatUser = res.data;
        console.log(this.chatUser);
      });
    },

    send() {
      let box = $("#im-box");
      if (!this.chatUser.username) {
        this.$message({
          type: "warning",
          message: "请选择聊天对象",
        });
        return;
      }
      if (!this.text) {
        this.$message({
          type: "warning",
          message: "请输入内容",
        });
      } else {
        let that = this;
        box.append(
          $(
             `<p style="margin:30px 0;float: right;clear: both;"><el-row>` +
              `<span style="margin-right:20px; border: 1px solid  rgba(23, 177, 31, 0.295);
                    background-color:  rgba(22, 177, 86, 0.199);
                    border-radius:60px ;
                    color: rgb(96, 170, 12);
                    padding: 10px;">${this.text}</span>`+
                  `<img src="http://39.108.99.135:9999/files/${that.user.userImages}" alt="" style="width: 80px; height: 80px; border-radius: 50%;">` +
                  `</el-row></p>`
          )
        );
        this.sendMessage(this.chatUser.username, this.text);
        this.text = "";
      }
    },
  },
};
</script>

<style scoped>
.text {
  font-size: 30px;
  color: pink;
}
textarea .el-textarea__inner{
  background-color:rgba(28, 158, 209, 0.404)
}
</style>